<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="资讯标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入资讯标题"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="资讯类型" prop="infoType">
        <el-select v-model="queryParams.infoType" placeholder="请选择资讯类型" clearable style="width: 100px;">
          <el-option
            v-for="dict in info_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发布状态" prop="status"  clearable style="width: 200px">
        <el-select v-model="queryParams.status" placeholder="请选择发布状态" clearable>
          <el-option
            v-for="dict in publish_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['healthSys:info:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['healthSys:info:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="infoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="资讯ID" align="center" prop="infoId" />
      <el-table-column label="资讯标题" align="center" prop="title" />
      <el-table-column label="资讯作者" align="center" prop="userName" />
      <el-table-column label="资讯内容"  align="center" :min-width="120" class-name="content-column">
        <template #default="scope">
          <div class="content-wrapper">
            <el-tooltip 
              effect="dark" 
              :content="cleanHtml(scope.row.content)" 
              placement="top-start"
              :disabled="!scope.row.content"
            >
              <div class="content-text">
                {{ cleanHtml(scope.row.content) || '-' }}
              </div>
            </el-tooltip>
          </div>
        </template>
        </el-table-column>
        <el-table-column label="封面" align="center" prop="coverImg" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.coverImg" :width="50" :height="50"/>
        </template>
      </el-table-column>
        <el-table-column label="资讯类型" align="center" prop="infoType">
        <template #default="scope">
          <dict-tag :options="info_type" :value="scope.row.infoType"/>
        </template>
      </el-table-column>
      <el-table-column label="分类" align="center" prop="categoryId">
        <template #default="scope">
          {{ getCategoryName(scope.row.categoryId) }}
        </template>
      </el-table-column>
      <el-table-column label="发布状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="publish_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="发布时间" align="center" prop="publishTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.publishTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['healthSys:info:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['healthSys:info:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改资讯管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="infoRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="资讯标题" prop="title">
          <el-input v-model="form.title" placeholder="请输入资讯标题" />
        </el-form-item>
        <el-form-item label="资讯内容">
          <editor v-model="form.content" :min-height="192"/>
        </el-form-item>
        <el-form-item label="封面图" prop="coverImg">
          <image-upload v-model="form.coverImg"/>
        </el-form-item>
        <el-form-item label="资讯类型" prop="infoType">
          <el-select v-model="form.infoType" placeholder="请选择资讯类型">
            <el-option
              v-for="dict in info_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-select 
            v-model="form.categoryId" 
            placeholder="请选择分类"
            filterable
            clearable
          >
            <el-option
              v-for="item in categoryList"
              :key="item.categoryId"
              :label="item.categoryName"
              :value="item.categoryId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="发布状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择发布状态">
            <el-option
              v-for="dict in publish_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="记录日期" prop="publishTime">
          <el-date-picker
            v-model="form.publishTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="选择日期"
            :disabled-date="disabledDate"
            class="w-full"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  
</template>

<script setup name="Info">
import { listInfo, getInfo, delInfo, addInfo, updateInfo } from "@/api/healthSys/info";
import { listCategory } from "@/api/healthSys/category";

const { proxy } = getCurrentInstance();
const { info_type, publish_status } = proxy.useDict('info_type', 'publish_status');

// 添加清理HTML标签的工具函数
const cleanHtml = (html) => {
  if (!html) return '';
  // 移除所有HTML标签，保留文本内容
  return html.replace(/<[^>]*>/g, '');
}

const infoList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    title: null,
    infoType: null,
    categoryId: null,
    status: null,
  },
  rules: {
    title: [
      { required: true, message: "资讯标题不能为空", trigger: "blur" }
    ],
    content: [
      { required: true, message: "资讯内容不能为空", trigger: "blur" }
    ],
    infoType: [
      { required: true, message: "资讯类型不能为空", trigger: "change" }
    ],
    categoryId: [
      { required: true, message: "分类不能为空", trigger: "change" }
    ],
    status: [
      { required: true, message: "发布状态不能为空", trigger: "change" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询资讯管理列表 */
function getList() {
  loading.value = true;
  listInfo(queryParams.value).then(response => {
    infoList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

const disabledDate = (time) => {
  return time.getTime() > Date.now()
}
// 表单重置
function reset() {
  form.value = {
    infoId: null,
    title: null,
    content: null,
    coverImg: null,
    infoType: null,
    categoryId: null,
    status: null,
    publishTime: null,
    remark: null
  };
  proxy.resetForm("infoRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.infoId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加资讯管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _infoId = row.infoId || ids.value
  getInfo(_infoId).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改资讯管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["infoRef"].validate(valid => {
    if (valid) {
      if (form.value.infoId != null) {
        updateInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addInfo(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _infoIds = row.infoId || ids.value;
  proxy.$modal.confirm('是否确认删除资讯管理编号为"' + _infoIds + '"的数据项？').then(function() {
    return delInfo(_infoIds);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('healthSys/info/export', {
    ...queryParams.value
  }, `info_${new Date().getTime()}.xlsx`)
}
// 获得分类列表
const categoryList = ref([]);
function getCategoryList() {
  listCategory().then(response => {
    categoryList.value = response.rows;
  }).catch(error => {
    proxy.$modal.msgError("分类加载失败");
  });
}
function getCategoryName(categoryId) {
  const category = categoryList.value.find(item => item.categoryId === categoryId);
  return category ? category.categoryName : '未知分类';
}
getCategoryName();
getCategoryList();
getList();
</script>
<style scoped>
.content-column .cell {
  max-height: 60px; /* 限制最大高度 */
}

.content-wrapper {
  display: -webkit-box;
  -webkit-line-clamp: 3; /* 限制显示行数 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.5;
  max-height: 60px;
}

.content-text {
  word-break: break-word; /* 允许换行 */
}
</style>
